package com.cfets.annualAssessment.backgroundController;

import com.cfets.annualAssessment.entity.AccountRole;
import com.cfets.annualAssessment.entity.Role;
import com.cfets.annualAssessment.entity.RoleRes;
import com.cfets.annualAssessment.entity.TableContainer;
import com.cfets.annualAssessment.service.AccountService;
import com.cfets.annualAssessment.service.RoleResService;
import com.cfets.annualAssessment.service.RoleService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by ShenYiChou on 2016/12/16.
 */
@Controller
@RequestMapping("/admin/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleResService roleResService;

    @Autowired
    private AccountService accountService;

    @RequestMapping("/index")
    public String index(Model model){
        return "role";
    }

    @RequestMapping(value = "/Get",method = RequestMethod.POST)
    public ResponseEntity<?> roleList(Role role){
        List<Role> roleList = roleService.getRolePage(role);
        TableContainer tableContainer = new TableContainer();
        tableContainer.setAaData(roleList);
        tableContainer.setiTotalDisplayRecords(role.getTotalCount());
        tableContainer.setiTotalRecords(role.getTotalCount());
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);
    }

    @RequestMapping(value = "/roleres",method = RequestMethod.GET)
    public ResponseEntity<?> roleReslist(RoleRes roleRes){
        List<RoleRes> roleResList=roleResService.findResByRole(roleRes.getRoleId());
        return new ResponseEntity<>(roleResList, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<?> createOrUpdate(@Valid Role role, BindingResult result) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if (result.hasErrors()) {
            return new ResponseEntity<>(result.getAllErrors(), HttpStatus.OK);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date();
        String str=sdf.format(date);
        role.setPostTime(str);

        List<RoleRes> roleResList = Lists.newArrayList();
        Field[] field = role.getClass().getDeclaredFields();
        for (int i = 0; i < field.length; i++){
            String name = field[i].getName();
            System.out.println(name);
            if (name.indexOf("Res") == 0){
                Method m = role.getClass().getMethod("get" + name);
                String value = (String) m.invoke(role);
                System.out.println(value);
                if (value != null) {
                    RoleRes roleRes = new RoleRes();
                    roleRes.setRoleId(role.getRoleName());
                    roleRes.setResourceId(name.substring(3,4));
                    roleResList.add(roleRes);
                }
            }
        }
        List<RoleRes> roleResBaseList=roleResService.findResByRole(role.getRoleName());
        boolean flag1 = this.roleResService.deleteMultiRoleRes(roleResBaseList);
        boolean flag2 = this.roleResService.insertMultiRoleRes(roleResList);


        boolean flag = false;
        if(role.getId()!=null && role.getId()!=0){
            flag = this.roleService.updateRole(role);
        }else {
            flag = this.roleService.newRole(role);
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteRole(@PathVariable("id") int id){
        AccountRole accountRole = new AccountRole();
        accountRole.setRole_id(id);
        //-1 用户组存在用户，请先删除相关用户
        if(!accountService.getAccountRoleList(accountRole).isEmpty()){
            return new ResponseEntity<>(-1, HttpStatus.OK);
        }
        List<RoleRes> roleResList = this.roleResService.findResByRoleId(id);
        boolean flag1 = this.roleResService.deleteMultiRoleRes(roleResList);
        boolean flag = this.roleService.deleteRoleById(id);
        if (!flag1){
            flag = false;
        }
        return new ResponseEntity<>(flag, HttpStatus.OK);
    }
}
